<!-- 新增/修改考勤组-考勤豁免 -->
<template>
  <main class="wrap">
    <header>
      <h2>豁免人员</h2>
      <a-button type="primary" @click="show">设置</a-button>
    </header>
    <div class="personnel">
      <template v-for="personnel in personnelList" :key="personnel">
        <div class="item">
          {{ personnel.name }}
          <icon-close-circle
            @click="del(personnel.userId as number, personnel.id)"
            :size="20"
            style="margin: 0 10px; cursor: pointer"
          />
        </div>
      </template>
    </div>
    <p
      v-if="applicableEmployeesExist.data.length !== 0"
      style="font-size: 12px; color: #f19e43; margin: 0; padding-left: 5px"
    >
      选择人员中，有
      {{ applicableEmployeesExist.data.length }}
      人由于已加入其他考勤组，未新增成功
      <span style="color: #409eff; cursor: pointer" @click="visible = true"
        >立即查看</span
      >
    </p>
    <header>
      <h2>豁免部门</h2>
      <a-button type="primary" @click="isDepartmentShow">设置</a-button>
    </header>
    <TableTurn
      style="width: 100%"
      :isShowPagination="false"
      :tableData="getTableDataDepartment"
      ref="tableRefDepartment"
    >
      <a-table-column align="center" data-index="name" title="部门名称">
      </a-table-column>
      <a-table-column
        align="center"
        data-index="attendanceTeamMember"
        title="在此考勤组人数"
      >
      </a-table-column>
      <a-table-column
        align="center"
        data-index="notAttendanceTeamMember"
        title="未在此考勤组人数"
      >
        <template #cell="{ record, rowIndex }">
          <p
            style="color: #409eff; cursor: pointer"
            @click="
              record?.notAttendanceTeamMember &&
                changeDepartmentList(record.notAttendanceTeamData, rowIndex)
            "
          >
            {{ record?.notAttendanceTeamMember }}
          </p>
        </template>
      </a-table-column>
    </TableTurn>
  </main>
  <OrganizationPersonnel
    ref="organizationPersonnel"
    :selected-ids="personnelIds.data"
    @changePersonnel="changePersonnel"
  />
  <OrganizationDepartment
    ref="organizationDepartment"
    :selected-ids="departmentIds.data"
    @changePersonnel="changeDepartment"
  />
  <a-drawer
    :width="450"
    :visible="visible"
    @ok="handleOk"
    @cancel="visible = false"
    unmountOnClose
  >
    <template #title> 未在此考勤组人员 </template>
    <a-space direction="vertical" fill>
      以下成员已加入其他考勤组，请选择是否加入此考勤组
      <TableTurn
        :isShowPagination="false"
        :tableData="getTableData"
        ref="tableRef"
        :args="{
          rowSelection: {
            type: 'checkbox',
            showCheckedAll: true,
            onlyCurrent: false
          }
        }"
      >
        <a-table-column align="center" data-index="name" title="姓名">
        </a-table-column>
        <a-table-column align="center" data-index="name" title="所在考勤组">
          <template #cell="{ record }">
            {{ record?.attendanceTeam?.name || '暂无' }}
          </template>
        </a-table-column>
      </TableTurn>
    </a-space>
  </a-drawer>
  <a-drawer
    :width="450"
    :visible="departmentVisible"
    @ok="handleDepartmentVisibleOk"
    @cancel="departmentVisible = false"
    unmountOnClose
  >
    <template #title> 未在此考勤组人员 </template>
    <a-space direction="vertical" fill>
      以下成员已加入其他考勤组，请选择是否加入此考勤组
      <TableTurn
        :isShowPagination="false"
        :tableData="getDepartmentTableData"
        ref="tableRefDepartmentList"
        :args="{
          rowSelection: {
            type: 'checkbox',
            showCheckedAll: true,
            onlyCurrent: false
          }
        }"
      >
        <a-table-column align="center" data-index="name" title="姓名">
        </a-table-column>
        <a-table-column align="center" data-index="name" title="所在考勤组">
          <template #cell="{ record }">
            {{ record?.attendanceTeam?.name || '暂无' }}
          </template>
        </a-table-column>
      </TableTurn>
    </a-space>
  </a-drawer>
</template>

<script lang="ts" setup>
import { GetSectionPersonnel } from '@/apis/management/human/baseSetting/leaveSetting';
import {
  GetAttendanceRemitUserList,
  PostRemit
} from '@/apis/attendance/base-setting/index';
interface Tlist {
  id?: number;
  attendanceTeamId?: number;
  userId?: number;
  departmentId?: number;
  applicableEmployee?: number;
  applicableDepartment?: number;
  type?: number;
  name?: string;
}

const route = useRoute();
const organizationPersonnel = ref();
const organizationDepartment = ref();
const tableRefDepartmentList = ref();
const tableRefDepartment = ref();
const tableRef = ref();

const departmentVisible = ref(false);
const list = ref<Tlist[]>([]);
const visible = ref(false);
const changeDepartmentListIndex = ref(0);
let personnelIds: { data: number[] } = reactive({ data: [] });

const departmentIds: { data: number[] } = reactive({ data: [] });
const departmentData: { data: any[] } = reactive({ data: [] });
const departmentList: { data: any[] } = reactive({ data: [] });

let applicableEmployeesExist: { data: any[] } = reactive({ data: [] });
const changePersonnel = (data: any) => {
  personnelIds.data = data.ids;
  list.value = list.value.filter(
    ({ applicableEmployee }) => applicableEmployee !== 1
  );
  data.data.forEach(({ id, departmentId, name }: any) => {
    list.value.push({
      attendanceTeamId: 0,
      userId: id,
      name,
      departmentId: departmentId,
      applicableEmployee: 1,
      applicableDepartment: 2,
      type: 2
    });
  });
};
const personnelList = computed(() =>
  list.value.filter(({ applicableEmployee }) => applicableEmployee === 1)
);
const delIds: number[] = [];
const del = (userId: number, id: number | void) => {
  list.value.splice(
    list.value.findIndex(({ userId: delId }: any) => delId === userId),
    1
  );
  personnelIds.data = personnelIds.data.filter((delId) => delId !== userId);
  if (id) {
    delIds.push(id);
  }
};

const getTableDataDepartment = () => {
  try {
    return departmentData.data;
  } catch (error) {
    console.log(error);
    return [];
  }
};

const getDepartmentTableData = () => {
  try {
    return departmentList.data;
  } catch (error) {
    console.log(error);
    return [];
  }
};

const getTableData = () => {
  try {
    return applicableEmployeesExist.data;
  } catch (error) {
    console.log(error);
    return [];
  }
};

const changeDepartment = async (data: any) => {
  departmentIds.data = data.ids;
  departmentData.data.length = 0;
  for (const item of data.data) {
    const departmentList = await GetSectionPersonnel({
      type: item.node === '部门' ? 2 : 1,
      typeName: item.id
    });

    const newData: any = { name: item.name };
    newData.attendanceTeamMember = departmentList.filter(({ id }: any) =>
      personnelIds.data?.includes(id)
    ).length;
    newData.notAttendanceTeamData = departmentList.filter(
      ({ id }: any) => !personnelIds.data?.includes(id)
    );
    newData.notAttendanceTeamMember = newData.notAttendanceTeamData.length;
    departmentData.data.push(newData);
  }
};

const changeDepartmentList = (data: any, rowIndex: number) => {
  departmentList.data = data;
  departmentVisible.value = true;
  changeDepartmentListIndex.value = rowIndex;
};

const id = route.query.id;

const show = () => {
  organizationPersonnel.value.show();
};
const isDepartmentShow = () => {
  organizationDepartment.value.show();
};

const handleDepartmentVisibleOk = () => {
  if (
    tableRefDepartmentList.value.selectedListData &&
    tableRefDepartmentList.value.selectedListData.length !== 0
  ) {
    tableRefDepartmentList.value.selectedListData.forEach(
      ({ id, departmentId }: any) => {
        list.value.push({
          attendanceTeamId: 0,
          userId: id,
          departmentId,
          type: 2,
          applicableEmployee: 2,
          applicableDepartment: 1
        });
      }
    );
    const length = tableRefDepartmentList.value.selectedListData.length;
    departmentData.data[changeDepartmentListIndex.value].notAttendanceTeamData =
      departmentData.data[
        changeDepartmentListIndex.value
      ].notAttendanceTeamData.filter(
        ({ id }: any) => !tableRefDepartmentList.value.selectedList.includes(id)
      );
    departmentData.data[changeDepartmentListIndex.value].attendanceTeamMember =
      departmentData.data[changeDepartmentListIndex.value]
        .attendanceTeamMember + length;
    departmentData.data[
      changeDepartmentListIndex.value
    ].notAttendanceTeamMember =
      departmentData.data[changeDepartmentListIndex.value]
        .notAttendanceTeamMember - length;
    tableRefDepartment.value.loadData();
  }
  departmentList.data = [];
  changeDepartmentListIndex.value = 0;
  departmentVisible.value = false;
};
const handleOk = () => {
  if (
    tableRef.value.selectedListData &&
    tableRef.value.selectedListData.length !== 0
  ) {
    tableRef.value.selectedListData.forEach(
      ({ id, userId, departmentId, name }: any) => {
        list.push({
          id,
          name,
          userId,
          departmentId,
          type: 1,
          applicableEmployee: 1,
          applicableDepartment: 2
        });
      }
    );
    applicableEmployeesExist.data = applicableEmployeesExist.data.filter(
      ({ id }: any) => !tableRef.value.selectedList.includes(id)
    );
    tableRef.value.loadData();
  }
  visible.value = false;
};

const save = async () => {
  await PostRemit({ list: list.value, deleteIds: delIds });
  // if (form.id) {
  //   // await PutClasses(form);
  // } else {
  //   // await PostClasses(form);
  // }
};

onMounted(async () => {
  const { content } = await GetAttendanceRemitUserList({ type: 2 });
  const isdepartmentIds = [];
  content.forEach(async ({ attendanceTeamMember, name }: any) => {
    list.value.push({ ...attendanceTeamMember, name });
    if (attendanceTeamMember.applicableEmployee === 1) {
      personnelIds.data.push(attendanceTeamMember.userId);
    } else {
      isdepartmentIds.push({
        id: attendanceTeamMember.departmentId,
        node: attendanceTeamMember.department.node,
        name: attendanceTeamMember.department.name
      });
      const map = new Map();
      const newArr = isdepartmentIds.filter(
        (v: any) => !map.has(v.id) && map.set(v.id, v)
      );
      isdepartmentIds.length = 0;
      newArr?.forEach((ele: any) => {
        isdepartmentIds.push(ele);
      });
    }
  });
  for (const iterator of isdepartmentIds) {
    const departmentList = await GetSectionPersonnel({
      type: iterator.node === '部门' ? 2 : 1,
      typeName: iterator.id
    });
    const newData: any = { name: iterator.name };
    newData.attendanceTeamMember = departmentList.filter(({ id }: any) =>
      personnelIds.data?.includes(id)
    ).length;
    newData.notAttendanceTeamData = departmentList.filter(
      ({ id }: any) => !personnelIds.data?.includes(id)
    );
    newData.notAttendanceTeamMember = newData.notAttendanceTeamData.length;
    departmentData.data.push(newData);
  }
});
defineExpose({ save });
</script>

<style lang="less" scoped>
main {
  margin-bottom: 60px;
  overflow: hidden;
  padding: 10px 20px;

  header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f2f2f2;
    margin-bottom: 10px;

    h2 {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      // padding: 10px;

      &::before {
        content: '';
        display: inline-block;
        width: 7px;
        height: 30px;
        background-color: #165dff;
        margin-right: 10px;
      }
    }
  }
  .personnel {
    width: 100%;
    height: 300px;
    border: 1px solid #e4e4e4;
    border-radius: 5px;
    display: flex;
    flex-wrap: wrap;
    padding: 20px;
    box-sizing: border-box;

    .item {
      display: flex !important;
      font-size: 18px;
    }
  }
}
:deep(.arco-table-th),
:deep(.arco-table-td) {
  height: 60px;
}
:deep(.arco-collapse-item-content) {
  background-color: #fff;
}
</style>
